package flc.ast.adapter;

import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartBean;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartType;

import flc.ast.R;
import stark.common.basic.adaptermutil.StkProviderMultiAdapter;
import stark.common.basic.view.RoundImageView;

/**
 * Author：daizhongbin on 2023/7/26
 * Email：1027154338@qq.com
 * Desc:
 */
public class FormatPartAdapter extends StkProviderMultiAdapter<AvatarPartBean> {
    private int selPos = -1;
    private AvatarPartType partType;

    public FormatPartAdapter(AvatarPartType partType, int spanCount) {
        super(spanCount);
        this.partType = partType;
        addItemProvider(new ItemProvider());
    }

    public void setSelPos(int selPos) {
        if (this.selPos != selPos) {
            this.selPos = selPos;
            notifyDataSetChanged();
        }
    }

    private class ItemProvider extends BaseItemProvider<AvatarPartBean> {

        @Override
        public int getItemViewType() {
            return StkProviderMultiAdapter.TYPE_VIEW;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_cam_avatar_part;
        }

        @Override
        public void convert(@NonNull BaseViewHolder holder, AvatarPartBean bean) {
            int pos = holder.getAdapterPosition();
            holder.itemView.setSelected(selPos == pos);

            ImageView ivImg = holder.getView(R.id.ivImg);
            ImageView ivSelector = holder.getView(R.id.ivSelector);
            RoundImageView ivImg1 = holder.getView(R.id.ivImg1);
            if (TextUtils.isEmpty(bean.getImgUri())) {
                ivImg.setBackgroundResource(0);
                ivImg.setImageResource(bean.getImgId());
                return;
            }

            if (selPos == pos) {
                ivSelector.setImageResource(R.drawable.part_sel);
            } else {
                ivSelector.setImageResource(R.drawable.part_bg);
            }
            ivImg.setBackgroundResource(0);
            if (partType == AvatarPartType.body) {
                int imgId = getContext().getResources().getIdentifier(bean.getImgNameWithNoExtension(), "drawable", getContext().getPackageName());
                Glide.with(ivImg).load(imgId).into(ivImg);
            } else {
                Glide.with(ivImg).load(Uri.parse(bean.getImgUri())).into(ivImg);
            }
        }
    }
}
